package org.example.javax.security.jaas.demo1;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.security.PrivilegedAction;

/**
-Djava.security.manager
-Djava.security.policy==/Users/juntaozhang/src/hello-java/JavaSE/src/main/java/org/example/javax/security/jaas/demo1/policy.txt
-Djava.security.auth.login.config==/Users/juntaozhang/src/hello-java/JavaSE/src/main/java/org/example/javax/security/jaas/demo1/example.conf
 */
public class MyClient {
  public static void main(String argv[]) {
    LoginContext ctx = null;
    try {
      ctx = new LoginContext("WeatherLogin", new MyCallbackHandler());
      try {
        ctx.login();
      } catch (LoginException le) {
        System.out.println("Authentication failed. " + le.getMessage());
        System.exit(-1);
      }
    } catch (LoginException | SecurityException le) {
      System.err.println("LoginContext cannot be created. " + le.getMessage());
      System.exit(-1);
    }
    System.out.println("Authentication succeeded.");

    Subject subject = ctx.getSubject();
    Subject.doAsPrivileged(subject, new PrivilegedAction() {
      @Override
      public Object run() {
        File file = new File("/Users/juntaozhang/src/hello-java/data/max.txt");
        if (file.exists()) {
          System.out.println("The file exists in the current working directory");
        } else {
          System.out.println("The file does not exist in the current working directory");
        }
        return null;
      }
    }, null);
    Subject.doAs(subject, new PrivilegedAction<Object>() {
      @Override
      public Object run() {
        File file = new File("/Users/juntaozhang/src/hello-java/data/max.txt");
        if (file.exists()) {
          System.out.println("The file exists in the current working directory");
        } else {
          System.out.println("The file does not exist in the current working directory");
        }
        return null;
      }
    });
    try {
      ctx.logout();
    } catch (LoginException le) {
      System.out.println("Logout: " + le.getMessage());
    }

  }
}
